import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import createLogger from 'vuex/dist/logger'
import getters from './getters'
import SecureLS from 'secure-ls'

const ls = new SecureLS({ isCompression: false })
const debug = process.env.NODE_ENV !== 'production'

Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', false, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

// createPersistedState({ storage: window.sessionStorage })
const createPersisted = createPersistedState({
  storage: {
    getItem: key => ls.get(key),
    setItem: (key, value) => ls.set(key, value),
    removeItem: key => ls.remove(key)
  }
})

export default new Vuex.Store({
  modules,
  getters,
  plugins: debug ? [createLogger(), createPersisted] : [createPersisted]
})
